package com.miao.hong.fang.base.dao;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;

import com.miao.hong.fang.util.pagination.ListAndCount;
import com.miao.hong.fang.util.pagination.PaginationContext;
import com.miao.hong.fang.util.pagination.PaginationSortOrderData;

public class PaginationEnabler {

	public static ListAndCount queryForList(HibernateTemplate hibernateTemplate, DetachedCriteria detachedCriteria) {
		
		PaginationSortOrderData data = PaginationContext.getPaginationSortOrderData();
		
		int firstResult = data.getCurrentPage() * data.getPageSize() - data.getPageSize();		
		List list = hibernateTemplate.findByCriteria(detachedCriteria, firstResult, data.getPageSize());
		
		ListAndCount result = new ListAndCount();
		result.setList(list);
		result.setCount(getCount(hibernateTemplate, detachedCriteria));
		
		return result;
	}
	
	private static int getCount(HibernateTemplate hibernateTemplate, final DetachedCriteria detachedCriteria) {
		
		return (Integer) hibernateTemplate.executeWithNativeSession(new HibernateCallback() {
			
			public Object doInHibernate(Session session) {
				
				Criteria criteria = detachedCriteria.getExecutableCriteria(session);
				
                criteria.setFirstResult(0);
                criteria.setMaxResults(Integer.MAX_VALUE);

                Integer rowCount = (Integer) criteria.setProjection(Projections.rowCount()).uniqueResult();

                return rowCount;
			}
		});
	}
	
}
